 <?php

class FirstCharPinYin {
	
	private static $FirstTable = array(
			0xB0C5, 0xB2C1, 0xB4EE, 0xB6EA, 0xB7A2, 0xB8C1, 0xB9FE, 0xBBF7, 0xBFA6, 0xC0AC, 0xC2E8,
			0xC4C3, 0xC5B6, 0xC5BE, 0xC6DA, 0xC8BB, 0xC8F6, 0xCBFA, 0xCDDA, 0xCEF4, 0xD1B9, 0xD4D1,0xD7FA
	);
	private static $FirstLetter = "ABCDEFGHJKLMNOPQRSTWXYZ";
	//区位表第二部份,不规则的,下面的字母是每个区里面对应字的拼音首字母.从网上查询整理出来的,可能会有部份错误.
	//56区-87区
	private static $SecondTable = array(
			"CJWGNSPGCGNEGYPBTYYZDXYKYGTZJNMJQMBSGZSCYJSYYFPGKBZGYDYWJKGKLJSWKPJQHYJWRDZLSYMRYPYWWCCKZNKYYG",
			"TTNGJEYKKZYTCJNMCYLQLYPYSFQRPZSLWBTGKJFYXJWZLTBNCXJJJJTXDTTSQZYCDXXHGCKBPHFFSSTYBGMXLPBYLLBHLX",
			"SMZMYJHSOJNGHDZQYKLGJHSGQZHXQGKXZZWYSCSCJXYEYXADZPMDSSMZJZQJYZCJJFWQJBDZBXGZNZCPWHWXHQKMWFBPBY",
			"DTJZZKXHYLYGXFPTYJYYZPSZLFCHMQSHGMXXSXJYQDCSBBQBEFSJYHWWGZKPYLQBGLDLCDTNMAYDDKSSNGYCSGXLYZAYPN",
			"PTSDKDYLHGYMYLCXPYCJNDQJWXQXFYYFJLEJPZRXCCQWQQSBZKYMGPLBMJRQCFLNYMYQMSQYRBCJTHZTQFRXQHXMQJCJLY",
			"QGJMSHZKBSWYEMYLTXFSYDXWLYCJQXSJNQBSCTYHBFTDCYZDJWYGHQFRXWCKQKXEBPTLPXJZSRMEBWHJLBJSLYYSMDXLCL",
			"QKXLHXJRZJMFQHXHWYWSBHTRXXGLHQHFNMGYKLDYXZPYLGGSMTCFBAJJZYLJTYANJGBJPLQGSZYQYAXBKYSECJSZNSLYZH",
			"ZX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YYCXNNCSYBZBFGLZZXSWMSCCMQNJQSBDQSJTXXMBLTXZCLZSHZCXRQJGJYLXZFJPHYMZQQYDFQJJLZZNZJCDGZYG",
			"CTXMZYSCTLKPHTXHTLBJXJLXSCDQXCBBTJFQZFSLTJBTKQBXXJJLJCHCZDBZJDCZJDCPRNPQCJPFCZLCLZXZDMXMPHJSGZ",
			"GSZZQLYLWTJPFSYASMCJBTZYYCWMYTZSJJLJCQLWZMALBXYFBPNLSFHTGJWEJJXXGLLJSTGSHJQLZFKCGNNNSZFDEQFHBS",
			"AQTGYLBXMMYGSZLDYDQMJJRGBJTKGDHGKBLQKBDMBYLXWCXYTTYBKMRTJZXQJBHLMHMJJZMQASLDCYXYQDLQCAFYWYXQHZ",
	);
	function utf8_to_gbk($string)//编码转换,必须转换成GB2312字符,这里只是简单的判断并不是很准确,可以自己写一个.
	{
		if (mb_check_encoding($string,'gb2312'))
			return $string;
		if (function_exists('iconv'))
			return iconv("utf-8","gb2312//IGNORE",$string);
		return mb_convert_encoding($string,'gb2312','utf-8');
	}
	
	function conv($str)
	{
		$str = self::utf8_to_gbk($str);
		$len = strlen($str);
		$newStr = '';
		for($i=0; $i<$len ; ++$i)
		{
			$H = ord($str[$i]);
			$L = ord($str[$i+1]);
			//字符集非法
			if ($H < 0xB0 ||  $L < 0xA1 || $H > 0xF7 || $L == 0xFF)
			{
				$newStr .= $str[$i];
				continue;
			}
			if ($H < 0xD8)//($H >= 0xB0 && $H <=0xD7)//查询文字在一级汉字区(16-55)
			{
				$W = ($H << 8) | $L;
				foreach(self::$FirstTable as $key=>$value)
				{
					if ($W < $value)
					{
						$newStr .= self::$FirstLetter[$key];
						break;
					}
				}
			}
			else// if (H >= 0xD8 && H <= 0xF7)//查询中文在二级汉字区(56-87)
				$newStr .=self::$SecondTable[$H - 0xD8][$L-0xA1];
			++$i;
		}
		return $newStr;
	}

	
}